import { login, logout, getInfo } from '@/api/user';
import { getToken, setToken, removeToken } from '@/utils/auth';
import { resetRouter } from '@/router';

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    loginId: '',
    description: '',
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN(state, token) {
    state.token = token;
  },
  SET_NAME(state, name) {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_USER_ID: (state, userId) => {
    state.loginId = userId;
  },
  SET_DESCRIPTION: (state, description) => {
    state.description = description;
  },
};

const actions = {
  // user login
  async login({ commit }, userInfo) {
    const { username, password } = userInfo;
    let result = await login({ username: username.trim(), password: password });
    if (result.code == 200) {
      commit('SET_TOKEN', result.data.tokenInfo.tokenValue);
      setToken(result.data.tokenInfo.tokenValue);
      return result;
    } else {
      throw new Promise.reject(new Error(result.message));
    }
  },

  // get user info
  async getInfo({ commit, state }) {
    // 根据token 获取用户信息
    let result = await getInfo(state.token);
    const { data } = result;
    if (!data) {
      return new Promise.reject('Verification failed, please Login again.');
    }
    const {
      userInfo: { id, name, avatar, description },
    } = data;
    commit('SET_NAME', name);
    commit('SET_AVATAR', avatar);
    commit('SET_USER_ID', id);
    commit('SET_DESCRIPTION', description);
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          removeToken(); // must remove  token  first
          resetRouter();
          commit('RESET_STATE');
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken(); // must remove  token  first
      commit('RESET_STATE');
      resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
